//
//  NewsModel.m
//  QWwyNews
//
//  Created by Amisear on 15/10/2.
//  Copyright © 2015年 Amisear. All rights reserved.
//

#import "NewsModel.h"
#import "networkTools.h"
#import "objc/runtime.h"
#import "NSObject+Extension.h"

@implementation NewsModel

//+ (instancetype)ObjectWithDict:(NSDictionary *)dict {
//    
//    id obj = [[self alloc]init];
//    //需要指定的模型内容
//    //创建数组 //里面存放需要获得的模型内容key
//    NSArray *propertis = [self.class loadPropertis];
//    //遍历寻找
//    for (NSString *key in propertis) {
//        //给obj 设值对应传进来的字典中的对应key的内容
//        if (dict[key] != nil) {
//            [obj setValue:dict[key] forKeyPath:key];
//        }
//        
//    }
//    
//  //  [obj setValuesForKeysWithDictionary:dict];
//    
//    return obj;
//}

//动态加载'类'的属性
//const char *kPropertiesKey = "kPropertiesKey";

//+ (NSArray *)loadPropertis {
//    
//    NSArray *plist = objc_getAssociatedObject(self, kPropertiesKey);
//    if (plist != nil) {
//        return plist;
//    }
//    unsigned int count = 0;
//    objc_property_t *list = class_copyPropertyList([self class], &count);
//    
//    //遍历数组
//    NSMutableArray *arrayM =[NSMutableArray arrayWithCapacity:count];
//    for (unsigned int i = 0; i < count; ++i) {
//        objc_property_t pkj = list[i];
//        
//        const char *cname = property_getName(pkj);
//        
//        //添加到数组
//        [arrayM addObject:[NSString stringWithUTF8String:cname]];
//    }
//    
//    free(list);
//    
//    objc_setAssociatedObject(self, kPropertiesKey, arrayM, OBJC_ASSOCIATION_COPY_NONATOMIC);
//    
//    
//    return objc_getAssociatedObject(self, kPropertiesKey);
//}

- (NSString *)description {
    
    NSArray *propertis = [self.class loadPropertis];
    //输入一组 key 输出对应key 的内容
    NSDictionary *d = [self dictionaryWithValuesForKeys:propertis];
    
    return [NSString stringWithFormat:@"<%@: %p> %@",self.class,self,d];
}

+ (void)loadNewsListWithURL:(NSString *)urlString finished:(void(^)(NSArray *))finished{
    
    [[networkTools sharedNetWorkTools] GET:urlString parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        // url 不同，第一层字典的 key 不同
        // 利用 keyEnumerator.nextObject 能够拿到 第一个 key
        // 主要用来遍历字典
        NSArray *array = responseObject[responseObject.keyEnumerator.nextObject];
//        [self newsWithDict:responseObject];
        
//        NSLog(@"%@",array);
        
        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
        
        for (NSDictionary *d in array) {
            [arrayM addObject:[self ObjectWithDict:d]];
        }
        
        //完成回调
        finished(arrayM.copy);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}



@end
